﻿using DefaultModels;
using SqlSugar;
using SqlSugar.IOC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CKS.PLC.Core;
using CKS.PLC.Core;

namespace ZR.DataCollection2.Services
{
    public class OEEService
    {

        public int BlockDb = 1000;
        public int DeviceStateStart = 0;
        public int DeviceModeStart = 0;

        ISqlSugarClient db;
        public OEEService() {
            this.db = DbScoped.SugarScope.GetConnection(0);
        }
        /// <summary>
        /// 监听PLC数据
        /// </summary>
        /// <param name="plc">PLC对象</param>
        /// <returns></returns>
        public async Task PlcRunOEE(PlcClient plc)
        {
            /*
             PLC专门设个DB块 用来交互OEE数据
             */
            if (plc != null)
            {
                var IsConnected = plc.plcSession.IsConnected;

                int? deviceState;//设备状态
                int? deviceMode;//设备模式
                int? lastState = 0;//最后一次状态
                #region 开始时间、结束时间
                //DateTime totalTime = DateTime.Now;//总时间开始
                //DateTime stopTime = DateTime.Now;//停止时间开始
                //DateTime waitTime = DateTime.Now;//等待时间开始
                //DateTime faultTime = DateTime.Now;//错误时间开始
                DateTime? totalTime = null;//总时间结束
                DateTime? stopTime = null;//停止时间结束
                DateTime? waitTime = null;//等待时间结束
                DateTime? faultTime = null;//错误时间结束
                #endregion
                while (IsConnected)
                {
                    await Task.Delay(500);
                    deviceState = plc.ReadInt16(BlockDb, DeviceStateStart);
                    deviceMode = plc.ReadInt16(BlockDb, DeviceModeStart);
                    /*
                     运行状态：1=空闲，2=运行中，3=故障；4=待料中；
                     设备模式：1=空模式；2=手动；4=初始化；8=自动；16=自动模式下暂停;
                     ************良率、实际生产数量->PLC直接给************
                     */
                    if (deviceMode == 8 || deviceMode == 2/*8*/)//自动时间状态下才计时
                    {
                        if (deviceState == 16 && deviceState != lastState)//空闲
                        {
                            waitTime = DateTime.Now;
                           // AddLogEventHandler?.Invoke("当前运行状态自动模式下暂停");
                        }
                        else if (deviceState == 2 && deviceState != lastState)//运行中
                        {
                            totalTime = DateTime.Now;
                           // AddLogEventHandler?.Invoke("当前运行状态运行中");
                        }
                        else if (deviceState == 3 && deviceState != lastState)//故障
                        {
                            faultTime = DateTime.Now;
                          //  AddLogEventHandler?.Invoke("当前运行状态故障");
                        }
                        else if (deviceState == 4 && deviceState != lastState)//待料中
                        {
                            stopTime = DateTime.Now;
                           // AddLogEventHandler?.Invoke("当前运行状态待料中");
                        }
                        if (deviceState != lastState)//互锁
                        {
                           // AddLogEventHandler?.Invoke("进入OEE互锁条件");
                            if (lastState != 0)
                            {
                                // AddLogEventHandler?.Invoke("OEE准备保存操作");
                                CksPerformancerecord model = new CksPerformancerecord()
                                {
                                    TotalRunTime = (float)(DateTime.Now - (totalTime == null ? DateTime.Now : totalTime))?.TotalMinutes,
                                    StopTime = (float)(DateTime.Now - (stopTime == null ? DateTime.Now : stopTime))?.TotalMinutes,
                                    WaitingTime = (float)(DateTime.Now - (waitTime == null ? DateTime.Now : waitTime))?.TotalMinutes,
                                    FaultTime = (float)(DateTime.Now - (faultTime == null ? DateTime.Now : faultTime))?.TotalMinutes
                                };
                                var dataSaveResult = db.Insertable(model).ExecuteReturnIdentity();
                                await Task.Delay(1000);
                                if (dataSaveResult >0)
                                {
                                    switch (lastState)
                                    {
                                        case 16:
                                            waitTime = null;
                                            break;
                                        case 2:
                                            totalTime = null;
                                            break;
                                        case 3:
                                            faultTime = null;
                                            break;
                                        case 4:
                                            stopTime = null;
                                            break;
                                    }
                                    //上传成功
                                    //AddLogEventHandler?.Invoke($"OEE数据保存成功，运行时间：{model.TotalRunTime}，停止时间：{model.StopTime}，等待时间：{model.WaitingTime}，故障时间：{model.FaultTime}");
                                }
                                else
                                {
                                    //AddLogEventHandler?.Invoke("OEE数据保存失败，可能未与服务器建立连接");
                                }
                            }
                            lastState = deviceState;
                        }
                    }
                    else if (deviceMode == 2)
                    {
                        //Task.Delay(500);
                        //AddLogEventHandler?.Invoke("当前运行模式手动");
                    }
                    else
                    {

                    }
                    //GC.Collect();
                }
            }
        }

    }
}
